package com.zhouhailin.captcha.controller;

import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author zhouhailin
 * @date 2022/12/16 15:42
 */
@RestController
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Resource
    private Producer producer;

    /**
     * 获取验证码
     */
    @GetMapping(value = "/captcha", produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {

        response.setContentType("image/jpeg");
        String text = producer.createText();
        logger.info("生成的验证码：" + text);
        request.getSession().setAttribute("code", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(image, "jpg", sos);
        } catch (IOException e) {
            logger.error("流异常。", e);
        }
    }

    /**
     * 登录
     *
     * @param code    验证码
     * @param request 请求参数
     * @return
     */
    @PostMapping("/login")
    public String login(String code, HttpServletRequest request) {
        // 获取生成的验证码
        String captcha = request.getSession().getAttribute("code").toString();
        logger.info("获取session中存储的验证码：" + captcha);
        if (code == null || code == "") {
            return "验证码不能为空";
        }
        if (null != captcha) {
            if (captcha.toLowerCase().equals(code.toLowerCase())) {
                return "验证码校验通过";
            }
        }

        return "验证码校验不通过";
    }
}
